<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语音录制应用 - 录音列表</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <script>
        // 全局错误处理，防止浏览器扩展冲突
        window.addEventListener('error', function(event) {
            // 检查错误是否来自扩展
            if (event.filename && event.filename.includes('chrome-extension://')) {
                // 阻止错误传播
                event.stopPropagation();
                event.preventDefault();
                console.warn('已拦截来自浏览器扩展的错误:', event.message);
                return true;
            }
        }, true);
        
        // 拦截未处理的Promise错误
        window.addEventListener('unhandledrejection', function(event) {
            // 检查错误是否与消息端口相关
            if (event.reason && event.reason.message && 
                (event.reason.message.includes('message port') || 
                 event.reason.message.includes('port closed'))) {
                // 阻止错误传播
                event.stopPropagation();
                event.preventDefault();
                console.warn('已拦截消息端口错误:', event.reason.message);
                return true;
            }
        });
    </script>
    <style>
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .header h1 {
            margin: 0;
        }
        .recordings-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        .recording-card {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            transition: transform 0.2s;
        }
        .recording-card:hover {
            transform: translateY(-5px);
        }
        .recording-info {
            padding: 15px;
        }
        .recording-title {
            font-size: 1.2rem;
            margin: 0 0 10px 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .recording-meta {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 10px;
        }
        .recording-actions {
            display: flex;
            border-top: 1px solid #eee;
        }
        .action-btn {
            flex: 1;
            padding: 10px;
            border: none;
            background-color: transparent;
            cursor: pointer;
            font-weight: bold;
            transition: background-color 0.2s;
        }
        .action-btn:hover {
            background-color: #f5f5f5;
        }
        .action-btn.play {
            color: #3498db;
        }
        .action-btn.download {
            color: #2ecc71;
        }
        .action-btn.delete {
            color: #e74c3c;
        }
        .waveform {
            height: 80px;
            background-color: #f5f5f5;
            position: relative;
        }
        .waveform-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .empty-state {
            text-align: center;
            padding: 50px;
            background-color: #f9f9f9;
            border-radius: 8px;
        }
        .empty-state h2 {
            margin-top: 0;
            color: #666;
        }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            background-color: #3498db;
            color: white;
        }
        .audio-player {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: #fff;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px;
            display: none;
        }
        .audio-player.active {
            display: block;
        }
        .player-controls {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .player-info {
            flex: 1;
            margin: 0 15px;
        }
        .player-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .player-progress {
            height: 5px;
            background-color: #eee;
            border-radius: 3px;
            overflow: hidden;
            margin-top: 10px;
        }
        .player-progress-fill {
            height: 100%;
            background-color: #3498db;
            width: 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>录音列表</h1>
            <a href="/" class="btn">返回录音</a>
        </div>
        
        <div id="recordingsContainer">
            <!-- 录音列表将通过JavaScript动态加载 -->
            <div class="empty-state">
                <h2>加载中...</h2>
            </div>
        </div>
    </div>
    
    <div class="audio-player" id="audioPlayer">
        <div class="player-controls">
            <button id="playerPlayPause" class="action-btn play" data-i18n="pause">暂停</button>
            <div class="player-info">
                <div class="player-title" id="playerTitle">录音标题</div>
                <div class="player-time">
                    <span id="playerCurrentTime">0:00</span> / <span id="playerDuration">0:00</span>
                </div>
                <div class="player-progress">
                    <div class="player-progress-fill" id="playerProgressFill"></div>
                </div>
            </div>
            <button id="playerClose" class="action-btn">关闭</button>
        </div>
        <audio id="audioElement"></audio>
    </div>
    
    <script>
        // 获取录音列表
        function fetchRecordings() {
            fetch('/api/recordings')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        const recordings = data.recordings;
                        const container = document.getElementById('recordingsContainer');
                        
                        if (recordings.length === 0) {
                            container.innerHTML = `
                                <div class="empty-state">
                                    <h2>暂无录音</h2>
                                    <p>返回首页录制新的音频</p>
                                    <a href="/" class="btn">开始录音</a>
                                </div>
                            `;
                            return;
                        }
                        
                        let html = '<div class="recordings-grid">';
                        recordings.forEach(recording => {
                            const filename = recording.filename;
                            const fileSize = recording.file_size;
                            const uploadTime = recording.upload_time;
                            
                            html += `
                                <div class="recording-card" data-filename="${filename}">
                                    <div class="waveform">
                                        <img src="https://via.placeholder.com/300x80/f5f5f5/3498db?text=Waveform" class="waveform-img" alt="波形图">
                                    </div>
                                    <div class="recording-info">
                                        <h3 class="recording-title">${filename}</h3>
                                        <div class="recording-meta">
                                            <div>大小: ${formatFileSize(fileSize)}</div>
                                            <div>上传时间: ${formatDate(uploadTime)}</div>
                                        </div>
                                    </div>
                                    <div class="recording-actions">
                                        <button class="action-btn play" data-filename="${filename}" data-title="${filename}">播放</button>
                                        <button class="action-btn download" data-filename="${filename}">下载</button>
                                        <button class="action-btn delete" data-filename="${filename}">删除</button>
                                    </div>
                                </div>
                            `;
                        });
                        html += '</div>';
                        
                        container.innerHTML = html;
                        
                        // 添加事件监听器
                        document.querySelectorAll('.action-btn.play').forEach(button => {
                            button.addEventListener('click', function() {
                                const filename = this.getAttribute('data-filename');
                                const title = this.getAttribute('data-title');
                                playRecording(filename, title);
                            });
                        });
                        
                        document.querySelectorAll('.action-btn.download').forEach(button => {
                            button.addEventListener('click', function() {
                                const filename = this.getAttribute('data-filename');
                                downloadRecording(filename);
                            });
                        });
                        
                        document.querySelectorAll('.action-btn.delete').forEach(button => {
                            button.addEventListener('click', function() {
                                const filename = this.getAttribute('data-filename');
                                deleteRecording(filename);
                            });
                        });
                    }
                })
                .catch(error => console.error('获取录音列表失败:', error));
        }
        
        // 播放录音
        function playRecording(filename, title) {
            const audioPlayer = document.getElementById('audioPlayer');
            const audioElement = document.getElementById('audioElement');
            const playerTitle = document.getElementById('playerTitle');
            const playerPlayPause = document.getElementById('playerPlayPause');
            
            // 设置音频源
            audioElement.src = `/uploads/${filename}`;
            playerTitle.textContent = title;
            
            // 显示播放器
            audioPlayer.classList.add('active');
            
            // 播放音频
            audioElement.play();
            if (window.i18n) {
                playerPlayPause.textContent = window.i18n.translate('pause');
            } else {
                playerPlayPause.textContent = '暂停';
            }
            
            // 更新进度条
            updatePlayerProgress();
        }
        
        // 下载录音
        function downloadRecording(filename) {
            const link = document.createElement('a');
            link.href = `/uploads/${filename}`;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 删除录音
        function deleteRecording(filename) {
            if (confirm('确定要删除这个录音吗？此操作不可撤销。')) {
                fetch(`/api/recordings/${filename}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        alert('录音已删除');
                        fetchRecordings();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => console.error('删除录音失败:', error));
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 格式化时长
        function formatDuration(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
        }
        
        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString();
        }
        
        // 更新播放器进度
        function updatePlayerProgress() {
            const audioElement = document.getElementById('audioElement');
            const playerCurrentTime = document.getElementById('playerCurrentTime');
            const playerDuration = document.getElementById('playerDuration');
            const playerProgressFill = document.getElementById('playerProgressFill');
            
            // 监听音频事件
            audioElement.addEventListener('timeupdate', function() {
                const currentTime = audioElement.currentTime;
                const duration = audioElement.duration || 0;
                
                // 更新当前时间
                playerCurrentTime.textContent = formatDuration(currentTime);
                
                // 更新进度条
                const progress = (currentTime / duration) * 100;
                playerProgressFill.style.width = `${progress}%`;
            });
            
            audioElement.addEventListener('loadedmetadata', function() {
                playerDuration.textContent = formatDuration(audioElement.duration);
            });
            
            audioElement.addEventListener('ended', function() {
                document.getElementById('playerPlayPause').textContent = '播放';
            });
        }
        
        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            fetchRecordings();
            
            // 播放/暂停按钮事件
            document.getElementById('playerPlayPause').addEventListener('click', function() {
                const audioElement = document.getElementById('audioElement');
                if (audioElement.paused) {
                    audioElement.play();
                    if (window.i18n) {
                        this.textContent = window.i18n.translate('pause');
                    } else {
                        this.textContent = '暂停';
                    }
                } else {
                    audioElement.pause();
                    if (window.i18n) {
                        this.textContent = window.i18n.translate('play');
                    } else {
                        this.textContent = '播放';
                    }
                }
            });
            
            // 关闭按钮事件
            document.getElementById('playerClose').addEventListener('click', function() {
                const audioElement = document.getElementById('audioElement');
                const audioPlayer = document.getElementById('audioPlayer');
                audioElement.pause();
                audioPlayer.classList.remove('active');
            });
        });
    </script>
</body>
</html> 